#!/usr/bin/python
# 作者:龚华
# 2023年07月16日20时28分58秒
# -*- coding:utf-8 -*-

import random

import matplotlib.pyplot  as plt
#使用决策树的分类函数
desicionNode = dict(boxstyle="sawtooth",fc="0.8")  #定义文本框和箭头格式
leafNode = dict(boxstyle="round4",fc="0.8")
arrow_args = dict(arrowstyle="<-")

#绘制带箭头的注解
def plotNode(nodeTxt,centerPt,parentPt,nodeType):
    createPlot.ax1.annotate(nodeTxt,xy=parentPt,xycoords='axes fraction',xytext=centerPt,textcoords='axes fraction',
                            va="center",ha="center",bbox=nodeType,arrowprops=arrow_args)

def createPlot():
    """
    绘制结点
    :return:
    """

    fig = plt.figure(1,facecolor='white')  #创建一个新图形
    fig.clf()  #清空绘图区
    createPlot.ax1 = plt.subplot(111,frameon=False)  #ticks for demo purposes
    plotNode('a decision node',(0.5,0.1),(0.1,0.5),desicionNode)
    plotNode('a leaf node',(0.8,0.1),(0.3,0.8),leafNode)
    plt.show()

#字典类型的树的叶子节点数目
def getNumLeafs(myTree):
    """
    获取叶节点的数目
    :param myTree:
    :return:
    """
    numLeafs = 0

    #tree形式为{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}
    #list(myTree.keys())[0] = 'no surfacing'
    firstStr = list(myTree.keys())[0]  #获取myTree的第一个key

    #firstStr = 'no surfacing',value = {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}
    secondDict = myTree[firstStr]  #获取myTree的第一个key的value
    for key in secondDict.keys():
        if type(secondDict[key]).__name__=='dict':  #如果secondDict[key]是字典
            numLeafs += getNumLeafs(secondDict[key])  #递归调用getNumLeafs
        else:
            numLeafs += 1
    return numLeafs

def getTreeDepth(myTree):
    maxtdepth = 0
    firstStr = list(myTree.keys())[0]  #获取myTree的第一个key
    secondDict = myTree[firstStr]  #获取myTree的第一个key的value
    for key in secondDict.keys():
        if type(secondDict[key]).__name__=='dict':
            #如果secondDict[key]是字典，递归调用getTreeDepth
            thisDepth = 1+getTreeDepth(secondDict[key])
        else:
            thisDepth = 1
        if thisDepth>maxtdepth:
            maxtdepth = thisDepth
    return maxtdepth

#预先存储树信息，避免每次测试代码时都要从数据中创建树的麻烦
def retrieveTree(i):
    listOfTrees =[{'no surfacing': {0: 'no', 1: {'flippers': \
                    {0: 'no', 1: 'yes'}}}},
                  {'no surfacing': {0: 'no', 1: {'flippers': \
                    {0: {'head': {0: 'no', 1: 'yes'}}, 1: 'no'}}}}
                  ]
    return listOfTrees[i]

def plotMidText(cntrPt,parentPt,txtString):
    """

    :param cntrPt:
    :param parentPt:
    :param txtString:
    :return:
    """
    xMid = (parentPt[0]-cntrPt[0])/2.0+cntrPt[0]
    yMid = (parentPt[1]-cntrPt[1])/2.0+cntrPt[1]
    createPlot.ax1.text(xMid,yMid,txtString)

#为什么可以这样使用全局变量plotTree.xOff、plotTree.yOff、plotTree.totalW、plotTree.totalD，可以这样使用原因：
#python的函数本身也是对象，可以个函数绑定属性，来实现全局使用。
# 代码中plotTree.totalW = float(getNumLeafs(inTree))，就是通过给plotTree增加totalW属性，来实现totalW的全局使用。
# 给函数绑定属性，可以通过函数名.属性名来使用属性，这样就可以实现全局使用了。举例
# def func():
#     pass
# func.totalW = 10
# print(func.totalW)
# 10
# print(func.__dict__)
# {'totalW': 10, '__module__': '__main__', '__doc__': None}
# print(func.__dict__['totalW'])
# 10
# print(func.__dict__['totalW'].__class__)
# <class 'int'>
#print(func.__dir__())
#['__repr__', '__call__', '__get__', '__new__', '__closure__',
# '__doc__', '__globals__', '__module__', '__code__', '__defaults__',
# '__kwdefaults__', '__annotations__', '__dict__', '__name__', '__qualname__',
# 'totalW']
def plotTree(myTree,parentPt,nodeTxt):

    numLeafs = getNumLeafs(myTree)  #计算宽与高
    depth = getTreeDepth(myTree)  #计算树的深度

    firstStr = list(myTree.keys())[0]  #第一个关键字
    #中心位置
    #plotTree.xOff 是全局变量，plotTree.totalW是全局变量,plotTree.totalD是全局变量，
    #plotTree.yOff是全局变量，plotTree.xOff、plotTree.yOff是用来追踪已经绘制的节点位置的
    #plotTree.totalW、plotTree.totalD是用来计算树的宽度和高度的
    #plotTree.xOff、plotTree.yOff是用来追踪已经绘制的节点位置的


    cntrPt = (plotTree.xOff+(1.0+float(numLeafs))/2.0/plotTree.totalW,plotTree.yOff)  #中心位置

    plotMidText(cntrPt,parentPt,nodeTxt)  #标记子节点属性值

    plotNode(firstStr,cntrPt,parentPt,desicionNode)  #绘制节点

    secondDict = myTree[firstStr]  #下一个字典，也就是继续绘制子节点

    plotTree.yOff = plotTree.yOff-1.0/plotTree.totalD  #y偏移

    for key in secondDict.keys():

        if type(secondDict[key]).__name__=='dict':

            plotTree(secondDict[key],cntrPt,str(key))

        else:  #如果是叶子节点

            plotTree.xOff = plotTree.xOff+1.0/plotTree.totalW  #x偏移

            plotNode(secondDict[key],(plotTree.xOff,plotTree.yOff),cntrPt,leafNode)  #绘制叶子节点

            plotMidText((plotTree.xOff,plotTree.yOff),cntrPt,str(key))  #标记子节点属性值

    plotTree.yOff = plotTree.yOff+1.0/plotTree.totalD  #y偏移


#绘制决策树
def createPlot(inTree):
    fig = plt.figure(1,facecolor='white')  #创建新图形
    fig.clf()  #清空绘图区
    axprops = dict(xticks=[],yticks=[])  #去掉x、y轴
    createPlot.ax1 = plt.subplot(111,frameon=False,**axprops)  #绘制图像
    plotTree.totalW = float(getNumLeafs(inTree))  #获取树的宽度
    plotTree.totalD = float(getTreeDepth(inTree))  #获取树的深度
    plotTree.xOff = -0.5/plotTree.totalW;plotTree.yOff = 1.0;  #x偏移
    plotTree(inTree,(0.5,1.0),'')  #绘制树

    fileName ='tree'+str(random.randint(0,100))+'.png'
    fig.savefig('.\data\%s'%fileName)  #保存绘制结果


def test():
    myTree = retrieveTree(0)
    print('叶子节点数目：',getNumLeafs(myTree))
    print('树的深度：',getTreeDepth(myTree))
def test_createPlot():
    myTree = retrieveTree(0)
    createPlot(myTree)
if __name__ == '__main__':
    #测试getNumLeafs, getTreeDepth
    #test()

    #测试createPlot
    test_createPlot()